﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using App.Utilities.Web.Handlers;
using System.Data;
using CRMBiz;
using Newtonsoft.Json;
using System.Globalization;

namespace CRMWeb.WebServices.AM
{
    /// <summary>
    /// Summary description for Security
    /// </summary>
    public class Security : BaseHandler
    {
        public override void OnMethodInvoke(OnMethodInvokeArgs e)
        {
            context.Response.Cache.SetCacheability(HttpCacheability.ServerAndNoCache);
            context.Response.Cache.SetExpires(DateTime.MinValue);
            context.Response.Cache.SetNoStore();
            //e.Cancel = true;
            SetResponseContentType(ResponseContentTypes.HTML);
        }

        public override void AfterMethodInvoke(object result)
        {
            base.AfterMethodInvoke(result);
        }

        public void GetSecurityofLoans()
        {
            var pageIndex = string.IsNullOrEmpty(context.Request["page"]) ? 1 : int.Parse(context.Request["page"]);
            var pageSize = string.IsNullOrEmpty(context.Request["rows"]) ? 10 : int.Parse(context.Request["rows"]);
            int LoanID = string.IsNullOrEmpty(context.Request.QueryString["LoanID"]) ? 0 : int.Parse(context.Request.QueryString["LoanID"]);
            DataSet ds = SecurityHandler.GetSecurityofLoans(pageIndex, pageSize, LoanID);
            var total = (ds.Tables[0].Rows.Count > 0) ? Convert.ToInt32(ds.Tables[0].Rows[0]["Total"]) : 0;
            var SumVehicleValue = (ds.Tables[0].Rows.Count > 0) ? Convert.ToInt32(ds.Tables[0].Rows[0]["SumVehicleValue"]) : 0;
            var SumVehiclePayment = (ds.Tables[0].Rows.Count > 0) ? Convert.ToInt32(ds.Tables[0].Rows[0]["SumVehiclePayment"]) : 0;
            var strJson = JsonConvert.SerializeObject(ds.Tables[0]);
            strJson = "{\"total\":\"" + total.ToString() + "\",\"rows\":" + strJson + ",\"footer\":[{\"app_MotorYear\":\"Total\",\"app_MotorMaker\":\"\",\"app_MotorModel\":\"\",\"app_VehicleBadge\":\"\",\"app_VehicleBody\":\"\",\"app_VehicleColor\":\"\",\"app_VehicleValue\":" + SumVehicleValue + ",\"app_VehiclePayment\":" + SumVehiclePayment + ",\"app_DateofInterest\":\"\",\"app_RegoExpiry\":\"\",\"app_VehicleOwner\":\"\",\"app_MotorInsurance\":\"\",\"app_VehiclePlateNo\":\"\",\"app_VehicleVIN\":\"\",\"app_VehicleEngine\":\"\",\"app_Location\":\"\"}]}";
            //context.Response.ContentType = "text/json";
            context.Response.Write(strJson);
        }

        public void GetRealProperty()
        {
            var pageIndex = string.IsNullOrEmpty(context.Request["page"]) ? 1 : int.Parse(context.Request["page"]);
            var pageSize = string.IsNullOrEmpty(context.Request["rows"]) ? 10 : int.Parse(context.Request["rows"]);

            int LoanID = string.IsNullOrEmpty(context.Request.QueryString["LoanID"]) ? 0 : int.Parse(context.Request.QueryString["LoanID"]);

            DataSet ds = SecurityHandler.GetRealProperty(pageIndex, pageSize, LoanID);
            var total = (ds.Tables[0].Rows.Count > 0) ? Convert.ToInt32(ds.Tables[0].Rows[0]["Total"]) : 0;
            var SumPropertyValue = (ds.Tables[0].Rows.Count > 0) ? Convert.ToInt32(ds.Tables[0].Rows[0]["SumPropertyValue"]) : 0;
            var SumPropertyOwing = (ds.Tables[0].Rows.Count > 0) ? Convert.ToInt32(ds.Tables[0].Rows[0]["SumPropertyOwing"]) : 0;
            var strJson = JsonConvert.SerializeObject(ds.Tables[0]);
            strJson = "{\"total\":\"" + total.ToString() + "\",\"rows\":" + strJson + ",\"footer\":[{\"app_PropertyAddress\":\"Total\",\"app_PropertyTitleRef\":\"\",\"app_PropertyType\":\"\",\"app_PropertyInterest\":\"\",\"app_LodgDate\":\"\",\"app_PropertyStatus\":\"\",\"app_PropertyValue\":" + SumPropertyValue + ",\"app_PropertySource\":\"\",\"app_PropertyOwing\":" + SumPropertyOwing + ",\"app_PropertySource1\":\"\"}]}";

            //context.Response.ContentType = "text/json";
            context.Response.Write(strJson);
        }

        public bool SaveVehicleSecurity(int SecurityVehicleID, string VIN, string EngineNo, string VehicleRegNo, string VehicleColour, string VehicleBadge, string VehicleModel, string VehicleMake, int VehicleYear, string RegisteredOwner, string VehicleSecurityStatus, decimal VehicleValue, decimal VehicleOwning, string VehicleValueSource, string VehicleOwningSource, string ExpiryDate, string InsuranceType, string VehicleComment, int LoanID)
        {
            bool flag = false;
            try
            {
                DateTime dtExpiryDate = new DateTime();
                DateTimeFormatInfo dtfi = new DateTimeFormatInfo();
                dtfi.ShortDatePattern = "yyyy-MM-dd";
                dtfi.DateSeparator = "-";
                if (ExpiryDate != "")
                    dtExpiryDate = Convert.ToDateTime(ExpiryDate, dtfi);

                flag = SecurityHandler.saveVehicleSecurity(SecurityVehicleID, VIN, EngineNo, VehicleRegNo, VehicleColour, VehicleBadge, VehicleModel, VehicleMake, VehicleYear, RegisteredOwner, VehicleSecurityStatus, VehicleValue, VehicleOwning, VehicleValueSource, VehicleOwningSource, dtExpiryDate, InsuranceType, VehicleComment, LoanID);
            }
            catch (Exception)
            {
                throw;
            }
            return flag;
        }

        public bool UpdateVehicleComment(int Vehicleid, string VehicleComment)
        {
            bool flag = false;
            try
            {
                flag = SecurityHandler.UpdateVehicleComment(Vehicleid, VehicleComment);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return flag;
        }
        
        public bool UpdateCompanyComment(int Companyid, string CompanyComment)
        {
            bool flag = false;
            try
            {
                flag = SecurityHandler.UpdateCompanyComment(Companyid, CompanyComment);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return flag;
        }

        public bool UpdatePropertyComment(int Propertyid, string PropertyComment)
        {
            bool flag = false;
            try
            {
                flag = SecurityHandler.UpdatePropertyComment(Propertyid, PropertyComment);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return flag;
        }

        public bool savePropertySecurity(int SecurityPropertyID, string Address, string TitleRef, string PropertyType, string PropertyOwner, string PropertySecurityStatus, string InterestType, string LodgmentDate, string CompletionDate, decimal PropertyValue, decimal PropertyOwning, string PropertyValueSource, string PropertyOwningSource, string Mortgagee, string SubSequentParties, string PropertyComment, int LoanID)
        {
            bool flag = false;
            try
            {
                DateTime dtLodgmentDate = new DateTime();
                DateTime dtCompletionDate = new DateTime();
                DateTimeFormatInfo dtformate = new DateTimeFormatInfo();
                dtformate.ShortDatePattern = "yyyy-MM-dd";
                dtformate.DateSeparator = "-";
                if (LodgmentDate != "")
                    dtLodgmentDate = Convert.ToDateTime(LodgmentDate, dtformate);
                if (CompletionDate != "")
                    dtCompletionDate = Convert.ToDateTime(CompletionDate, dtformate);
                flag = SecurityHandler.savePropertySecurity(SecurityPropertyID, Address, TitleRef, PropertyType, PropertyOwner, PropertySecurityStatus, InterestType, dtLodgmentDate, dtCompletionDate, PropertyValue, PropertyOwning, PropertyValueSource, PropertyOwningSource, Mortgagee, SubSequentParties, PropertyComment, LoanID);
            }
            catch (Exception)
            {
                throw;
            }
            return flag;
        }

        public bool saveCompanySecurity(int SecurityCompanyID, string Company, string Security, string SecurityStatus, string RegistrationDate, decimal PriorChargee, decimal SubsequentChargee, string Comment, int LoanID)
        {
            bool flag = false;
            try
            {
                DateTime dtRegistrationDate = new DateTime();
                DateTimeFormatInfo dtformate = new DateTimeFormatInfo();
                dtformate.ShortDatePattern = "yyyy-MM-dd";
                dtformate.DateSeparator = "-";
                if (RegistrationDate != "")
                    dtRegistrationDate = Convert.ToDateTime(RegistrationDate, dtformate);
                flag = SecurityHandler.saveCompanySecurity(SecurityCompanyID, Company, Security, SecurityStatus, dtRegistrationDate, PriorChargee, SubsequentChargee, Comment, LoanID);
            }
            catch (Exception)
            {
                throw;
            }
            return flag;
        }

        public void GetSecurityForLoan(int Loanid)
        {
            var pageIndex = string.IsNullOrEmpty(context.Request["page"]) ? 1 : int.Parse(context.Request["page"]);
            var pageSize = string.IsNullOrEmpty(context.Request["rows"]) ? 10 : int.Parse(context.Request["rows"]);

            Double totalValue = 0;
            Double totalOwning = 0;
            DataSet ds = SecurityHandler.GetSecurityForLoan(pageIndex, pageSize, Loanid);

            var total = (ds.Tables[0].Rows.Count > 0) ? Convert.ToInt32(ds.Tables[0].Rows.Count) : 0;
            for (int i = 0; i < Convert.ToInt32(total); i++)
            {
                totalValue += Convert.ToDouble(ds.Tables[0].Rows[i]["Value"].ToString());
                totalOwning += Convert.ToDouble(ds.Tables[0].Rows[i]["Owning"].ToString());
            }

            var strJson = JsonConvert.SerializeObject(ds.Tables[0]);
            strJson = "{\"total\":\"" + total.ToString() + "\",\"rows\":" + strJson + ",\"footer\":[{\"SecurityType\":\"Total\",\"Security\":\"\",\"Value\":" + totalValue.ToString() + ",\"Owning\":" + totalOwning.ToString() + ",\"Owner\":\"\",\"Status\":\"\"}]}";
            context.Response.Write(strJson);
        }

        public void GetTotalSecurity(int LoanID)
        {
            int totalCount = SecurityHandler.GetTotalSecurity(LoanID);
            context.Response.Write(totalCount);
        }

        public void GetSecurityById(int securityid, string type)
        {
            DataSet ds = new DataSet();
            if (type == "Property")
            {
                ds = SecurityHandler.GetPropertySecurityById(securityid);
            }
            else if (type == "Vehicle")
            {
                ds = SecurityHandler.GetVehicleSecurityById(securityid);
            }
            else if (type == "Company")
            {
                ds = SecurityHandler.GetCompanySecurityById(securityid);
            }
            var strJson = JsonConvert.SerializeObject(ds.Tables[0]);
            context.Response.Write(strJson);
        }

        public void DeleteSecurityByID(int securityid, string type)
        {
            if (type == "Property")
            {
                SecurityHandler.DeletePropertySecurity(securityid);
            }
            else if(type == "Vehicle")
            {
                SecurityHandler.DeleteVehicleSecurity(securityid);
            }
            else if (type == "Company")
            {
                SecurityHandler.DeleteCompanySecurity(securityid);
            }
        }
    }
}